package leetcodev1.数组;

import java.util.HashMap;
import java.util.Map;

public class LeetCode1 {

    //暴力解法
    //双重循环
    public int[] twoSum1(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[]{-1, -1};
    }

    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> dict = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            //重复的元素取后一个
            dict.put(nums[i], i);
        }

        for (int i = 0; i < nums.length; i++) {
            if (dict.containsKey(target - nums[i])) {
                int index = dict.get(target - nums[i]);
                if (i == index) {
                    continue;
                }
                return new int[]{i, index};
            }
        }
        return new int[]{-1, -1};
    }

    //hash一遍就有结果了
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }

}
